package com.zyp.jobseeker.service.impl;
import com.zyp.jobseeker.mapper.PositionMapper;
import com.zyp.jobseeker.service.ApplicationService;
import com.zyp.jobseeker.mapper.ApplicationMapper;
import com.zyp.jobseeker.mapper.InterviewMapper;
import com.zyp.jobseeker.entity.Application;
import com.zyp.jobseeker.entity.Interview;
import com.zyp.jobseeker.enums.ApplicationStatus;
import com.zyp.jobseeker.enums.InterviewStatus;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApplicationServiceImpl implements ApplicationService {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationServiceImpl.class);

    @Autowired
    private ApplicationMapper applicationMapper;

    @Autowired
    private InterviewMapper interviewMapper;
    @Autowired
    private PositionMapper positionMapper;
    /**
     * 提交求职申请
     */
    @Override
    public Long submitApplication(Application application) {
        logger.info("[求职申请] 收到新申请提交，参数: {}", application);

        try {
            // 通过positionId获取enterpriseId
            Long enterpriseId = positionMapper.selectEnterpriseIdByPositionId(application.getPositionId());
            if (enterpriseId == null) {
                logger.warn("[求职申请] 岗位不存在或已删除，positionId: {}", application.getPositionId());
                throw new IllegalArgumentException("岗位不存在或已删除");
            }

            // 设置企业ID
            application.setEnterpriseId(enterpriseId);

            // 设置申请状态和时间
            application.setStatus(ApplicationStatus.PENDING);
            application.setApplyTime(new java.util.Date());

            // 提交申请
            int rowsAffected = applicationMapper.submitApplication(application);

            if (rowsAffected > 0) {
                logger.info("[求职申请] 申请提交成功，申请ID: {}", application.getId());
                return application.getId();
            } else {
                logger.warn("[求职申请] 申请提交失败");
                return null;
            }
        } catch (Exception e) {
            logger.error("[求职申请] 提交申请时发生异常", e);
            throw new RuntimeException("提交求职申请失败: " + e.getMessage());
        }
    }

    /**
     * 查询企业收到的求职申请
     */
    @Override
    public PageInfo<Map<String, Object>> getApplicationsByEnterprise(
            Long enterpriseId, Integer status, int page, int size) {
        logger.info("[求职申请] 收到企业申请查询请求，参数：enterpriseId={}, status={}, page={}, size={}",
                enterpriseId, status, page, size);

        try {
            // 开始分页查询
            PageHelper.startPage(page, size);
            List<Application> applications = applicationMapper.findApplicationsByEnterpriseId(enterpriseId, status);

            // 转换为Map结构
            PageInfo<Application> userPageInfo = new PageInfo<>(applications);
            PageInfo<Map<String, Object>> mapPageInfo = convertToMapPageInfo(userPageInfo);

            logger.info("[求职申请] 企业申请查询完成，返回结果数: {}", mapPageInfo.getTotal());
            return mapPageInfo;
        } catch (Exception e) {
            logger.error("[求职申请] 查询企业申请失败", e);
            throw new RuntimeException("查询企业申请失败: " + e.getMessage());
        }
    }

    /**
     * 拒绝求职申请
     */
    @Override
    public boolean rejectApplication(Long id) {
        logger.info("[求职申请] 收到申请拒绝请求，参数：id={}", id);

        try {
            // 验证申请是否存在
            Application application = applicationMapper.selectById(id);
            if (application == null) {
                logger.warn("[求职申请] 尝试拒绝不存在的申请，ID: {}", id);
                return false;
            }

            // 执行拒绝操作
            int rowsAffected = applicationMapper.rejectApplication(id);
            boolean success = rowsAffected > 0;

            if (success) {
                logger.info("[求职申请] 申请拒绝成功，ID: {}", id);
            } else {
                logger.warn("[求职申请] 申请拒绝失败，ID: {}", id);
            }

            return success;
        } catch (Exception e) {
            logger.error("[求职申请] 拒绝申请时发生异常", e);
            throw new RuntimeException("拒绝求职申请失败: " + e.getMessage());
        }
    }

    /**
     * 接受求职申请并生成面试邀请
     */
    @Transactional
    @Override
    public Map<String, Object> acceptApplication(Long id, Interview interview) {
        logger.info("[求职申请] 收到申请接受请求，参数：id={}, interview={}", id, interview);

        try {
            // 验证申请是否存在
            Application application = applicationMapper.selectById(id);
            if (application == null) {
                logger.warn("[求职申请] 尝试接受不存在的申请，ID: {}", id);
                return createErrorResult("申请不存在");
            }

            // 更新申请状态
            int updateRows = applicationMapper.acceptApplication(id);
            if (updateRows <= 0) {
                logger.warn("[求职申请] 更新申请状态失败，ID: {}", id);
                return createErrorResult("更新申请状态失败");
            }

            // 重新查询更新后的申请信息
            Application updatedApplication = applicationMapper.selectById(id);
            if (updatedApplication == null) {
                logger.warn("[求职申请] 无法获取更新后的申请信息，ID: {}", id);
                return createErrorResult("无法获取更新后的申请信息");
            }

            // 构建完整的面试信息
            buildInterview(interview, application);

            // 插入面试记录
            int insertRows = interviewMapper.insertInterview(interview);
            if (insertRows <= 0) {
                logger.warn("[求职申请] 插入面试记录失败，申请ID: {}", id);
                return createErrorResult("插入面试记录失败");
            }

            // 重新查询插入后的面试信息
            Interview insertedInterview = interviewMapper.selectById(interview.getId());
            if (insertedInterview == null) {
                logger.warn("[求职申请] 无法获取插入后的面试信息，面试ID: {}", interview.getId());
                return createErrorResult("无法获取插入后的面试信息");
            }

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("application", createApplicationResult(updatedApplication));
            result.put("interview", createInterviewResult(insertedInterview));

            logger.info("[求职申请] 申请接受成功，生成面试ID: {}", interview.getId());
            return result;
        } catch (Exception e) {
            logger.error("[求职申请] 处理申请接受时发生异常", e);
            throw new RuntimeException("处理求职申请失败: " + e.getMessage());
        }
    }

    /**
     * 查询学生自己的求职申请
     */
    @Override
    public PageInfo<Map<String, Object>> getApplicationsByStudent(
            Long studentId, Integer status, int page, int size) {
        logger.info("[求职申请] 收到学生申请查询请求，参数：studentId={}, status={}, page={}, size={}",
                studentId, status, page, size);

        try {
            // 开始分页查询
            PageHelper.startPage(page, size);
            List<Application> applications = applicationMapper.findApplicationsByStudentId(studentId, status);

            // 转换为Map结构
            PageInfo<Application> userPageInfo = new PageInfo<>(applications);
            PageInfo<Map<String, Object>> mapPageInfo = convertToMapPageInfo(userPageInfo);

            logger.info("[求职申请] 学生申请查询完成，返回结果数: {}", mapPageInfo.getTotal());
            return mapPageInfo;
        } catch (Exception e) {
            logger.error("[求职申请] 查询学生申请失败", e);
            throw new RuntimeException("查询学生申请失败: " + e.getMessage());
        }
    }

    /**
     * 将PageInfo<Application>转换为PageInfo<Map<String, Object>>
     */
    private PageInfo<Map<String, Object>> convertToMapPageInfo(PageInfo<Application> userPageInfo) {
        // 创建新的PageInfo并转换数据
        PageInfo<Map<String, Object>> mapPageInfo = new PageInfo<>
                (new ArrayList<>(), userPageInfo.getNavigatePages());

        // 复制基础分页信息
        mapPageInfo.setPageNum(userPageInfo.getPageNum());
        mapPageInfo.setPageSize(userPageInfo.getPageSize());
        mapPageInfo.setSize(userPageInfo.getSize());
        mapPageInfo.setTotal(userPageInfo.getTotal());
        mapPageInfo.setPages(userPageInfo.getPages());
        mapPageInfo.setPrePage(userPageInfo.getPrePage());
        mapPageInfo.setNextPage(userPageInfo.getNextPage());
        mapPageInfo.setIsFirstPage(userPageInfo.isIsFirstPage());
        mapPageInfo.setIsLastPage(userPageInfo.isIsLastPage());
        mapPageInfo.setNavigatePages(userPageInfo.getNavigatePages());
        mapPageInfo.setNavigatepageNums(userPageInfo.getNavigatepageNums());

        // 转换用户数据
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Application application : userPageInfo.getList()) {
            mapList.add(convertApplicationToMap(application));
        }

        mapPageInfo.setList(mapList);
        return mapPageInfo;
    }

    /**
     * 将Application对象转换为Map结构
     */
    private Map<String, Object> convertApplicationToMap(Application application) {
        Map<String, Object> applicationMap = new HashMap<>();
        applicationMap.put("id", application.getId());
        applicationMap.put("studentId", application.getStudentId());
        applicationMap.put("enterpriseId", application.getEnterpriseId());
        applicationMap.put("positionId", application.getPositionId());
        applicationMap.put("applyTime", application.getApplyTime());
        applicationMap.put("status", application.getStatus() != null ? application.getStatus().name() : null);
        applicationMap.put("remark", application.getRemark());
        //enterpriseName, positionName作为其他表的信息，只有非空时才放入
        if (application.getEnterpriseName() != null) {
            applicationMap.put("enterpriseName", application.getEnterpriseName());
        }
        if (application.getPositionName() != null) {
            applicationMap.put("positionName", application.getPositionName());
        }
        return applicationMap;
    }

    /**
     * 构建完整的面试信息
     */
    private void buildInterview(Interview interview, Application application) {
        interview.setApplicationId(application.getId());
        interview.setEnterpriseId(application.getEnterpriseId());
        interview.setStudentId(application.getStudentId());
        interview.setPositionId(application.getPositionId());
        interview.setStatus(InterviewStatus.PENDING_CONFIRM);
        interview.setInviteTime(new java.util.Date());
    }

    /**
     * 构建成功结果
     */
    private Map<String, Object> createApplicationResult(Application application) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", application.getId());
        result.put("status", application.getStatus() != null ? application.getStatus().name() : null);
        result.put("updateTime", new java.util.Date());
        return result;
    }

    /**
     * 构建面试结果
     */
    private Map<String, Object> createInterviewResult(Interview interview) {
        Map<String, Object> result = new HashMap<>();
        result.put("id", interview.getId());
        result.put("applicationId", interview.getApplicationId());
        result.put("status", interview.getStatus() != null ? interview.getStatus().name() : null);
        result.put("interviewTime", interview.getInterviewTime());
        result.put("interviewLocation", interview.getInterviewLocation());
        return result;
    }

    /**
     * 构建错误结果
     */
    private Map<String, Object> createErrorResult(String message) {
        Map<String, Object> result = new HashMap<>();
        result.put("code", 500);
        result.put("message", message);
        return result;
    }
}